<template>
  <div id="personalCenter">
    <div class="div">
      <el-form ref="personalCenterForm" :model="personalCenterForm" label-width="100px" class="selectForm" :rules="rules">

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="personalCenterForm.username" :disabled="true" />
            </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="personalCenterForm.name" placeholder="姓"/>
              </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
              <el-form-item label="登录密码">
                <el-button type="primary" @click="changePassword">修改密码</el-button>
              </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="手机">
              <el-input v-model="personalCenterForm.telNumber" placeholder="手机号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮件">
              <el-input v-model="personalCenterForm.email" placeholder="邮箱"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="头像">
              <div class="imgPr">
                <el-image 
                  class="img"
                  :src="personalCenterForm.headImg" 
                  :preview-src-list="previewImgList">
                </el-image>
                <div class="imgPa">
                  <el-upload
                    ref="upload"
                    :show-file-list="false"
                    :before-upload="beforUpload"
                    :http-request="uploadImageMethod"
                    :file-list="fileList"
                    list-type="picture"
                    action="#"
                    accept=".jpg,.png,.jpeg">
                    <el-button class="changeImg" style="padding: 0px;">
                      <i class="iconfont icon-tianjia"></i>
                    </el-button>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" >
              <el-select v-model="sex" placeholder="请选择" class="my-el-select" @change="changeSex" style="width:100%">
                <el-option
                  v-for="item in sexs"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        

        <el-form-item label="自我介绍" style="margin-top: 4vh">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4}"
            placeholder="自我介绍"
            v-model="personalCenterForm.introduce"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
        

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="注册时间">
              <el-input v-model="personalCenterForm.createTime" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后登录时间">
              <el-input v-model="personalCenterForm.lastLoginTime" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="角色" class="my-el-select">
              <el-select v-model="personalCenterForm.roles" multiple :disabled="true" placeholder="角色" style="width:100%">
                <el-option
                  v-for="item in roles"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24" style="text-align:right">
            <el-form-item> 
              <el-button type="primary" @click="onSubmit">提交</el-button>
              <el-button @click="onReturn">返回</el-button>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
    </div>

    <el-dialog title="修改密码" :visible.sync="dialogChangePassword" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="changePasswordForm" :rules="changePasswordRule" ref="changePasswordForm" class="changePassword">
        <el-form-item label="旧密码" :label-width="formLabelWidth" prop="oldPassword">
          <el-input v-model="changePasswordForm.oldPassword" show-password/>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="newPassword">
          <el-input v-model="changePasswordForm.newPassword" show-password/>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="confirmPassword">
          <el-input v-model="changePasswordForm.confirmPassword" show-password/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleChangePassword('changePasswordForm')">取 消</el-button>
        <el-button type="primary" @click="submitChangePassword('changePasswordForm')">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>

import {
  changeUserPassword,getCurrentUserInfo,editCurrentUserInfo,uploadImage,getAllRole
} from '@/assets/request/api.js';
import tool from '@/assets/js/tool'
export default {
  name: 'personalCenter',
  mixins: [tool],
  data() {
    
    var checkNewPassword = (rule, value, callback) => {
      if(!this.changePasswordForm.newPassword){
        callback("请输入新密码")
      } else if(this.changePasswordForm.newPassword != this.changePasswordForm.confirmPassword ){
        callback("两次密码不一致");
      } else {
        callback()
      }
    };

    var checkConfirmPassword = (rule,value,callback) => {
      if(!this.changePasswordForm.confirmPassword){
        callback("请确认密码")
      } else if(this.changePasswordForm.newPassword != this.changePasswordForm.confirmPassword){
        callback("两次密码不一致");
      } else {
        callback()
      }
    }

    return {
      fileList: [],
      previewImgList:[],
      rules: {
        name: [
          { required: true, message: '请输入姓', trigger: 'blur' },
        ],
      },
      personalCenterForm: {
        username: '',
        name: '',
        telNumber: '',
        email: '',
        headImg: '',
        sex: '',
        introduce: '',
        createTime: '',
        modifyTime: '',
        roles: [],
      },
      roles: [],
      changePasswordForm: {
        username: '',
        oldPassword:'',
        newPassword: '',
        confirmPassword: ''
      },
      formLabelWidth: '80px',
      sexs: [{
        value: true,
        label: '男'
      },{
        value: false,
        label: '女'
      }],
      sex: '',
      dialogChangePassword: false,
      changePasswordRule: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        newPassword: [
          { validator: checkNewPassword, trigger: 'blur',required:true},
        ],
        confirmPassword: [
          { validator: checkConfirmPassword, trigger: 'blur',required:true},
        ]
      }
    }
  },
  methods: {
    changeSex(value) {
      this.personalCenterForm.sex = value 
    },
    changePassword() {
      this.dialogChangePassword = true
    },
    onSubmit() {
      editCurrentUserInfo(this.personalCenterForm).then(res => {
        this.$message({
          message: "修改信息成功",
          type: "success"
        });
        this.initUserInfo()
        this.$router.go(-1)
      }).catch(err => {
        this.$message({
          message: err.message,
          type: "error"
        });
      })
    },
    onReturn() {
      this.$router.push("/home")
    },
    submitChangePassword(formName) {
      this.$refs[formName].validate((valid) => {

        if(valid){
          this.changePasswordForm.oldPassword = this.rsaEncryptByPublicKey(this.changePasswordForm.oldPassword)
          this.changePasswordForm.newPassword = this.rsaEncryptByPublicKey(this.changePasswordForm.newPassword)
          this.changePasswordForm.confirmPassword = this.rsaEncryptByPublicKey(this.changePasswordForm.confirmPassword)
          // 修改密码
          changeUserPassword(this.changePasswordForm).then(res => {

            this.$message({
              message: '修改密码成功',
              type: 'success'
            });
            this.dialogChangePassword = false
            this.initUserInfo()

          }).catch(err => {
              this.$message({
                message: err.message,
                type: 'error'
              });
          })

          this.$refs[formName].resetFields();

        } 
      }) 
    },
    cancleChangePassword(formName) {
      this.$refs[formName].resetFields()
      this.dialogChangePassword = false
    },
    async initUserInfo() {
      await getCurrentUserInfo().then(res => {
        this.personalCenterForm = res.data
        if(this.personalCenterForm.sex === true){
          this.sex = '男'
        }
        if(this.personalCenterForm.sex === false){
          this.sex = '女'
        }
        this.changePasswordForm.username = this.$store.state.user.userInfo.username
        this.initPerviewImg(this.personalCenterForm.headImg)
      }).catch(err => {
        this.$message({
            message: err.message,
            type: "error"
        });
      })
    },
    beforUpload(file) {
      // 校验文件格式
      if(file.type != 'image/png' && file.type !== 'image/jpg' && file.type !== 'image/jpeg') {
        this.$message({
            message: '不支持该格式',
            type: "error"
        });
        return false
      }

      if(Number(file.size / 1024 / 1024) > 5) {
        this.$message({
            message: '文件不允许超过5MB,请重新上传',
            type: "error"
        });
        return false
      }

      return true
    },
    uploadImageMethod(file) {
      let data = new FormData();
      data.append("file",file.file)
      uploadImage(data).then(res => {
        this.$message({
          message: '上传成功',
          type: 'success'
        });
        this.personalCenterForm.headImg = res.data.src
        this.initPerviewImg(this.personalCenterForm.headImg)
      }).catch(err => {
        this.$message({
          message: err.message,
          type: 'error'
        });
      })
    },
    initPerviewImg(src) {
      this.previewImgList = []
      this.previewImgList.push(src)
    }
  },
  mounted() {
    getAllRole().then(res => {
      this.roles = res.data.records
    }).catch(err => {
      this.$message({
        message: err.message,
        type: 'error'
      });
    })
    this.initUserInfo()
  },
}
</script>

<style lang="scss" scoped>

.div {
  width: 50vw;
  margin-left: 18%;
}

.selectForm /deep/ .el-form-item__label {
  font-size: 12px;
}

.el-form-item{
  margin-bottom: 0px;
}

.el-input /deep/ .el-input__inner{ 
  height: 32px;
  font-size: 13px;
  box-shadow: none;
  border: 1px solid #e9e9e9;
}

.el-row >>> .el-col {
  margin-top: 5vh;
}

.el-button {
  line-height: 0px;
  height: 32px;
  padding: 12px;
  font-size: 2px;
  border-radius: 20px;
}

.img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-top: 3px;
  border: 3px solid #f2f3f5;
  background: #619fe7;
}

.changeImg {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-left: 8px;
}

.imgPr {
  position: relative;
  display: inline-block;
  text-align: center;
}

.imgPa {
  position: absolute;
  left:0;
  top:0;
  right:0;
  margin-left: 36px;
  cursor: pointer;
  font-size: 22px;
}

.changePassword {
  .el-form-item{
    margin-bottom: 20px;
  }
}

</style>


<style lang="scss" >

/* 自定义宽度 */
#personalCenter {
  .my-el-select {
    .el-input__inner {
        height: 32px;
    }
  }
}

</style>
